import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Linking,
  ScrollView,
  ActivityIndicator,
  Image,
  Modal,
} from 'react-native';
import SafeTabBarWrapper from '../components/SafeTabBarWrapper';
import packageJson from '../../package.json';
import { commonAPI } from '../api';
import { ToastManager } from '../components/Toast';
import { COLORS, SHADOWS } from '../styles/constants';

export default function AboutScreen() {
  const [loading, setLoading] = useState(true);
  const [aboutData, setAboutData] = useState({
    appVersion: packageJson.version || '1.0.0',
    companyName: '贝拉文旅科技有限公司',
    companyNameEn: '',
    phone: '400-123-456',
    email: 'support@bellatravel.com',
    workingHours: '工作日 09:00 - 18:00',
    address: '',
    logoUrl: '',
    userAgreement: '',
    privacyPolicy: '',
  });

  // 协议弹窗状态
  const [agreementModal, setAgreementModal] = useState({
    visible: false,
    title: '',
    content: '',
  });

  // 组件加载时获取关于我们数据
  useEffect(() => {
    fetchAboutUsData();
  }, []);

  // 获取关于我们数据
  const fetchAboutUsData = async () => {
    try {
      const response = await commonAPI.getAboutUsList();

      // 解析数据
      const rows = response?.data?.data?.rows || [];
      const configData = {};

      rows.forEach(item => {
        configData[item.configKey] = item.configValue;
      });

      // 更新状态
      setAboutData({
        appVersion: configData.app_version || packageJson.version || '1.0.0',
        companyName: configData.company_name_cn || '贝拉文旅科技有限公司',
        companyNameEn: configData.company_name_en || '',
        phone: configData.consultation_phone || '400-123-456',
        email: configData.enterprise_email || 'support@bellatravel.com',
        workingHours: configData.working_hours || '工作日 09:00 - 18:00',
        address: configData.company_address || '',
        logoUrl: configData.company_logo_url || '',
        userAgreement: configData.user_agreement || '',
        privacyPolicy: configData.privacy_policy || '',
      });
    } catch {
      ToastManager.error('获取公司信息失败，显示默认信息');
    } finally {
      setLoading(false);
    }
  };

  const handleLinkPress = (type, value) => {
    if (type === 'email') {
      Linking.openURL(`mailto:${value}`).catch(() =>
        ToastManager.error('无法打开邮箱客户端'),
      );
    } else if (type === 'phone') {
      Linking.openURL(`tel:${value}`).catch(() =>
        ToastManager.error('无法拨打电话'),
      );
    }
  };

  const handleAgreementPress = type => {
    const content =
      type === 'privacy' ? aboutData.privacyPolicy : aboutData.userAgreement;
    const title = type === 'privacy' ? '隐私政策' : '用户协议';

    if (content) {
      setAgreementModal({
        visible: true,
        title,
        content,
      });
    } else {
      ToastManager.info('敬请期待');
    }
  };

  const closeAgreementModal = () => {
    setAgreementModal({
      visible: false,
      title: '',
      content: '',
    });
  };

  // 加载中状态
  if (loading) {
    return (
      <SafeTabBarWrapper style={{ backgroundColor: '#f5f6f8' }}>
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#ff6b35" />
          <Text style={styles.loadingText}>加载中...</Text>
        </View>
      </SafeTabBarWrapper>
    );
  }

  // 构建信息行数据
  const infoRows = [
    { label: '应用版本', value: aboutData.appVersion },
    { label: '应用名称', value: packageJson.name || 'BellaTravel' },
    { label: '公司名称', value: aboutData.companyName },
    { label: '邮箱', value: aboutData.email, type: 'email' },
    { label: '客服电话', value: aboutData.phone, type: 'phone' },
    { label: '客服时间', value: aboutData.workingHours },
  ];

  // 如果有地址信息，添加到列表中
  if (aboutData.address) {
    infoRows.push({ label: '公司地址', value: aboutData.address });
  }

  return (
    <SafeTabBarWrapper style={{ backgroundColor: '#f5f6f8' }}>
      <ScrollView
        style={styles.container}
        contentContainerStyle={styles.content}
      >
        <View style={styles.logoCard}>
          {aboutData.logoUrl ? (
            <Image
              source={{ uri: aboutData.logoUrl }}
              style={styles.logoImage}
              resizeMode="contain"
            />
          ) : (
            <View style={styles.logoCircle}>
              <Text style={styles.logoText}>B</Text>
            </View>
          )}
          <Text style={styles.appName}>{aboutData.companyName}</Text>
          {aboutData.companyNameEn ? (
            <Text style={styles.appNameEn}>{aboutData.companyNameEn}</Text>
          ) : null}
          <Text style={styles.appDesc}>
            一站式旅游导览服务，带你探索最美目的地
          </Text>
        </View>

        <View style={styles.card}>
          {infoRows.map((row, idx) => (
            <View key={row.label}>
              {/* 地址信息需要特殊处理，使用纵向布局 */}
              {row.label === '公司地址' ? (
                <View style={styles.infoRowVertical}>
                  <Text style={styles.infoLabel}>{row.label}</Text>
                  <Text style={styles.infoValueMultiline}>{row.value}</Text>
                </View>
              ) : (
                <View style={styles.infoRow}>
                  <Text style={styles.infoLabel}>{row.label}</Text>
                  <TouchableOpacity
                    onPress={() =>
                      row.type && handleLinkPress(row.type, row.value)
                    }
                    activeOpacity={row.type ? 0.7 : 1}
                  >
                    <Text
                      style={[styles.infoValue, row.type && styles.infoLink]}
                    >
                      {row.value}
                    </Text>
                  </TouchableOpacity>
                </View>
              )}
              {idx !== infoRows.length - 1 && <View style={styles.divider} />}
            </View>
          ))}
        </View>

        <View style={styles.card}>
          <Text style={styles.sectionTitle}>文旅理念</Text>
          <Text style={styles.paragraph}>
            我们致力于打造智能化、个性化的旅游导览体验，为旅客提供实时语音讲解、精选路线推荐、特色美食文化等一站式服务。
          </Text>
        </View>

        <View style={styles.card}>
          <Text style={styles.sectionTitle}>相关协议</Text>
          <TouchableOpacity
            style={styles.linkRow}
            activeOpacity={0.7}
            onPress={() => handleAgreementPress('privacy')}
          >
            <Text style={styles.linkText}>隐私政策</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.linkRow}
            activeOpacity={0.7}
            onPress={() => handleAgreementPress('user')}
          >
            <Text style={styles.linkText}>用户协议</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>

      {/* 协议内容弹窗 */}
      <Modal
        visible={agreementModal.visible}
        transparent
        animationType="fade"
        statusBarTranslucent
        hardwareAccelerated
        onRequestClose={closeAgreementModal}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContainer}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>{agreementModal.title}</Text>
            </View>

            <ScrollView
              style={styles.modalContent}
              showsVerticalScrollIndicator={true}
            >
              <Text style={styles.modalText}>{agreementModal.content}</Text>
            </ScrollView>

            <View style={styles.modalFooter}>
              <TouchableOpacity
                style={styles.modalButton}
                onPress={closeAgreementModal}
                activeOpacity={0.8}
              >
                <Text style={styles.modalButtonText}>知道了</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </SafeTabBarWrapper>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background.secondary,
  },
  content: {
    paddingBottom: 24,
    paddingHorizontal: 16,
    paddingTop: 20,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: COLORS.background.secondary,
  },
  loadingText: {
    marginTop: 12,
    fontSize: 14,
    color: COLORS.text.tertiary,
  },
  logoCard: {
    alignItems: 'center',
    backgroundColor: COLORS.background.card,
    borderRadius: 20,
    paddingVertical: 24,
    paddingHorizontal: 16,
    ...SHADOWS.sm,
    marginBottom: 20,
  },
  logoImage: {
    width: 100,
    height: 100,
    marginBottom: 8,
  },
  logoCircle: {
    width: 66,
    height: 66,
    borderRadius: 33,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: COLORS.primary,
  },
  logoText: {
    fontSize: 32,
    color: '#fff',
    fontWeight: '700',
  },
  appName: {
    fontSize: 18,
    fontWeight: '700',
    color: COLORS.text.primary,
    marginTop: 12,
    textAlign: 'center',
    paddingHorizontal: 16,
  },
  appNameEn: {
    fontSize: 12,
    color: COLORS.text.tertiary,
    marginTop: 4,
    textAlign: 'center',
    paddingHorizontal: 16,
  },
  appDesc: {
    marginTop: 8,
    fontSize: 13,
    color: COLORS.text.tertiary,
    textAlign: 'center',
    paddingHorizontal: 16,
  },
  card: {
    borderRadius: 20,
    backgroundColor: COLORS.background.card,
    padding: 20,
    ...SHADOWS.sm,
    marginBottom: 20,
  },
  infoRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 10,
  },
  infoRowVertical: {
    flexDirection: 'column',
    paddingVertical: 10,
  },
  infoLabel: {
    fontSize: 14,
    color: COLORS.text.tertiary,
    marginBottom: 0,
  },
  infoValue: {
    fontSize: 14,
    color: COLORS.text.primary,
    fontWeight: '500',
  },
  infoValueMultiline: {
    fontSize: 14,
    color: COLORS.text.primary,
    fontWeight: '500',
    marginTop: 6,
    lineHeight: 20,
  },
  infoLink: {
    color: COLORS.primary,
    textDecorationLine: 'underline',
  },
  divider: {
    height: StyleSheet.hairlineWidth,
    backgroundColor: COLORS.border.light,
  },
  sectionTitle: {
    fontSize: 16,
    color: COLORS.text.primary,
    fontWeight: '600',
    marginBottom: 10,
  },
  paragraph: {
    fontSize: 13,
    color: COLORS.text.secondary,
    lineHeight: 20,
  },
  linkRow: {
    paddingVertical: 12,
  },
  linkText: {
    fontSize: 15,
    color: COLORS.primary,
    fontWeight: '600',
  },
  // 协议弹窗样式
  modalOverlay: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: COLORS.background.overlay,
    padding: 20,
  },
  modalContainer: {
    backgroundColor: COLORS.background.card,
    borderRadius: 16,
    width: '100%',
    maxHeight: '80%',
    overflow: 'hidden',
    ...SHADOWS.lg,
  },
  modalHeader: {
    padding: 20,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border.light,
    alignItems: 'center',
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: COLORS.text.primary,
  },
  modalContent: {
    maxHeight: 400,
    paddingHorizontal: 20,
    paddingVertical: 16,
  },
  modalText: {
    fontSize: 14,
    color: COLORS.text.secondary,
    lineHeight: 22,
    textAlign: 'left',
  },
  modalFooter: {
    padding: 16,
    borderTopWidth: 1,
    borderTopColor: COLORS.border.light,
  },
  modalButton: {
    backgroundColor: COLORS.primary,
    paddingVertical: 12,
    paddingHorizontal: 32,
    borderRadius: 8,
    alignItems: 'center',
  },
  modalButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
});
